/**
 * Created by Xiaoming on 2017/9/4.
 */
angular.module('module.menu')
    .controller('MenuController', MenuController);
MenuController.$inject = ['$scope', '$state', '$cookies', '$stateParams', '$localStorage', 'ShopMenuService', 'ShopService', 'PrivilegeService', 'CouponService', 'OrderService', 'DeskService', 'AuthService','deskList','WxjssdkService'];
function MenuController($scope, $state, $cookies, $stateParams, $localStorage, ShopMenuService, ShopService, PrivilegeService, CouponService, OrderService, DeskService, AuthService,deskList,WxjssdkService) {
    var vm = this;
    vm.user = {};
    function activate(){
        //获取个人信息
        if ($cookies.get("_userId")) {
            AuthService.getuser($cookies.get("_userId")).$promise.then(function (data) {
                vm.user = data;
            })
        }
        var url = window.location.href;
        var trueurl = url;
        if (url.indexOf("#") > 0) {
            trueurl = url.substring(0, url.indexOf("#"));
        }
        //trueurl = trueurl.replace("store", "menu");
        //trueurl = trueurl.replace("&scope=true", "");
        var postinfo = {
            "component_appid": mall_userauth.component_appid,
            "mer_id": appid,
            "path": trueurl
            // "path": "http://o2o.shuwang.info/orderinfo/store/476429753?appid=wxa255fef7bd52511d&deskid=8 "
        };
        WxjssdkService.get_ticket(postinfo).$promise.then(function(wxconfig){
            ///*调起扫描二维码*/
            wx.config({
                debug: false,
                appId: appid,
                timestamp: wxconfig.timestamp,
                nonceStr: wxconfig.nonceStr,
                signature: wxconfig.signature,
                jsApiList: ['checkJsApi', 'scanQRCode']
            });//end_config

            wx.error(function (res) {
                // alert("出错了：" + JSON.stringify(res));
            });

            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['scanQRCode'],
                    success: function (res) {
                    }
                });
                //扫描二维码
                document.querySelector('#scanQRCode').onclick = function () {
                    wx.scanQRCode({
                        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                        success: function (res) {
                            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                            //结果截取桌台号
                            for (var i = 0; i < deskList.length; i++) {
                                var sceneStr;
                                try {
                                    if (JSON.parse(deskList[i].param)) {
                                        throw "success";
                                    } else {
                                        throw "error";
                                    }
                                }
                                catch (err) {
                                    if (err == "success")
                                        sceneStr = JSON.parse(deskList[i].param)
                                }
                                //alert(i+" "+deskList[i].stid+" "+deskList[i].sceneStr+" "+result)
                                if (sceneStr.wxqrcode == result) {
                                    //alert("找到",deskList[i].sceneStr,result)
                                    $scope.$apply(function () {
                                        //alert("进入apply")
                                        vm.deskid = deskList[i].stid;
                                        $cookies.put("deskid", vm.deskid);
                                        setdekid(vm.deskid)
                                    });
                                    break;
                                }
                            }
                        }
                    });
                };//end_document_scanQRCode

            });//end_ready
            ///*微信扫一扫结束*/
        });
    }
    setTimeout(function(){
        activate();
    },500);
    // alert(JSON.stringify(date.$promise))
    //没有订单信息强制回跳
    if($stateParams.order == null){
        var shopList = ShopMenuService.buyNowShopById($stateParams.shopid);
        if(!shopList){
            window.history.go(-1);
        }
        $stateParams.order = shopList;
    }
    //订单备注
    vm.remark = function (status) {
        if (status == "show") {
            transformAnimation("-100%", 200, ".payment_show");
            transformAnimation(0, 200, ".remark_content");
        } else if (status == "hide") {
            transformAnimation(0, 200, ".payment_show");
            transformAnimation("100%", 200, ".remark_content");
        }
    };
    vm.remark("hide");//初始化备注
    vm.shopid = $stateParams.shopid;
    var userid = $cookies.get("_userId");
    //deskid设置
    if(getdeskid() != null){
        vm.deskid = getdeskid();
    }else {
        vm.deskid = $stateParams.deskid;
    }
    vm.appid = $stateParams.appid;
    vm.order = $stateParams.order;
    if($stateParams.order){
        OrderService.delcache();//先清除缓存
        vm.order = $stateParams.order[0];
        //vm.goodscontent = vm.order.goodscontent;
        //vm.shopbuygoods = vm.order.list;
    }else {
        //$state.go("store",{shopid:$stateParams.shopid,deskid:$stateParams.deskid})
    }

    //获取商店信息
    ShopService.getShopByShopId(vm.shopid).$promise.then(function (shop) {
        vm.shops = shop;
        if (vm.shops.promotionList.length == 0) {
            var promotion = {
                "description": "本店暂无优惠活动"
            };
            vm.shops.promotionList.push(promotion);
        }
        //优惠券和优惠活动计算
        if(vm.order){
            vm.goodscontent = {
                totalprice: vm.order.goodscontent.totalprice,
                primecost: vm.order.goodscontent.primecost,
                promotionDiscount: 0,
                discountIntensity: '',
                promotionType: '',
                promotionid: '',
                promotionFull:0,
                couponDiscount: 0,
                couponid: '',
                paymentprice: vm.order.goodscontent.totalprice,
            };
            vm.couponList = [];
            vm.couponValidNum = 0;
            //优惠活动判断
            if(shop.promotionList.length>0&&!vm.order.goodscontent.hadDiscount){
                PrivilegeService.calcPromotion(vm.goodscontent, shop.promotionList);
            }
            //优惠券使用判断
            CouponService.validCoupon(shop.shopid,userid,vm.goodscontent,function(){
                vm.couponValidNum++;
            },function(couponList){
                vm.couponList = couponList;
            });
        }
    });

    //获取appid
    var appid = $stateParams.appid;
    if (!appid) {
        appid = mall_userauth.wxmp_appid;
    } else {
        mall_userauth.wxmp_appid = appid;
    }

    //快速备注内容
    vm.remarkList = [
        [
            {
                "text": "不要辣",
                "checked": false
            },
            {
                "text": "少点辣",
                "checked": false
            },
            {
                "text": "多点辣",
                "checked": false
            }
        ],
        [
            {
                "text": "饭多点",
                "checked": false
            },
            {
                "text": "饭少点",
                "checked": false
            }
        ],
        [
            {
                "text": "不要香菜",
                "checked": false
            }
        ],
        [
            {
                "text": "不要洋葱",
                "checked": false
            }
        ],
        [
            {
                "text": "多点醋",
                "checked": false
            }
        ],
        [
            {
                "text": "多点葱",
                "checked": false
            }
        ]
    ];
    //快速备注
    vm.addremark = function (remark, content, $event) {
        var self = $event.target;
        var parent = self.parentNode;
        if (content.checked) {
            content.checked = false;
            $(self).removeClass("selected");
        } else {
            $(parent).find(".switch-item").removeClass("selected");
            for (var i = 0; i < remark.length; i++) {
                remark[i].checked = false;
            }
            content.checked = true;
            $(self).addClass("selected");
        }
    };
    //快速备注确认按钮
    vm.sure_remark = function () {
        var remark_text = "";
        for (var i = 0; i < vm.remarkList.length; i++) {
            for (var j = 0; j < vm.remarkList[i].length; j++) {
                var remark = vm.remarkList[i][j];
                if (remark.checked) {
                    if (remark_text != "") {
                        remark_text += "，" + remark.text;
                    } else {
                        remark_text += remark.text;
                    }
                }
            }
        }
        if (vm.remarkText) {
            if (remark_text != "") {
                remark_text += "，" + vm.remarkText;
            } else {
                remark_text += vm.remarkText;
            }
        }
        vm.buyMessage = remark_text;
        vm.remark("hide");
    };
    //加菜按钮
    vm.moregoods = function () {
        $cookies.put("tag", "store");
        history.back();
    };

    //清空按钮
    vm.sure_clean = function () {
        $(".contain-item").fadeIn();
        vm.trash = function () {//清空
            ShopMenuService.removeShopById(vm.shopid);
            //vm.order = ShopMenuService.buyNowShopById(vm.shopid);
            //vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
            //OrderService.delcache();//先清除缓存
            //cacheinfo = OrderService.getCacheOreder();
            vm.order = null;
            vm.goodscontent = {};
            //vm.shopbuygoods = [];
            $(".contain-item").fadeOut();
            //in_out("out");
            // history.go(-1);
        }
    };
    vm.notrash = function () {
        $(".contain-item").fadeOut();
    };

    vm.buyMessage = '';

    //下单按钮
    vm.sure_click = function () {
        //$cookies.put("_userId",1469675141267);
        if(!$cookies.get("phone")){
            $state.go("wxuc",{openid:$cookies.get("openid")});
        }
        if (!$cookies.get("_userId")) {
            //input_alert("请先登录");
            if($cookies.get("openid")){
                $state.go("wxuc",{openid:$cookies.get("openid")});
            }
        } else if (!vm.order) {
            input_alert("您清单为空");
            return;
        } else if(!vm.deskid || vm.deskid == 0 || vm.deskid == null){
            input_alert("请选择桌台");
            return;
        }else {
            if (vm.goodscontent.totalprice == 0 || vm.goodscontent.totalprice == undefined) {
                alert('订单金额为0');
            } else {
                var accesscode = {
                    "appid":$cookies.get("appid"),
                    "openid":$cookies.get("openid")
                };
                var order = {
                    //buyerid: $cookies.get("_userId"),
                    creatorid: $cookies.get("_userId"),//测试环境
                    buyMessage: vm.buyMessage,
                    type: 6,
                    receiverName: vm.user.nickname,
                    receiverPhone: vm.user.phone,
                    //osid: vm.deskid,//新增的用来关联桌台的字段
                    /*receiverName: vm.sel_address.name + sex,
                     receiverPhone: vm.sel_address.phone,
                     receiverZip: vm.sel_address.zipcode,
                     receiverAddress: vm.sel_address.area + vm.sel_address.address,*/
                    accesscode: JSON.stringify(accesscode),
                    //extField:JSON.stringify(extField),
                    ordersShops : []
                };
                //var accesscode = $cookies.get('accesscode');
                loadCart(true, "leaveLoader");
                //document.getElementById('payOrder').setAttribute("disabled", "disabled");
                var goods_list = vm.order.list;
                var OrdersShopsReq = {
                    shopid:$stateParams.shopid,
                    osid: vm.deskid,//新增的用来关联桌台的字段
                    pnum: vm.pnum,//新增的用来关联用餐人数
                    ordersShopsGoods:[],
                    ordersShopsPrivileges:[]
                };
                for (var j = 0; j < goods_list.length; j++) {
                    var goods = goods_list[j];
                    OrdersShopsReq.ordersShopsGoods.push({
                        shopid: $stateParams.shopid,
                        goodsid: goods.goodsid,
                        skuid: goods.skuid,
                        fee: goods.price,
                        currentFee: goods.currentFee,
                        num: goods.num
                    });
                }
                if (vm.goodscontent.promotionid != '') {
                    var privilege = {
                        onsaleid: vm.goodscontent.promotionid,
                        onsale: vm.goodscontent.promotionDiscount,
                        type: 2
                    };
                    OrdersShopsReq.ordersShopsPrivileges.push(privilege);
                }
                if (vm.goodscontent.couponid != '') {
                    var privilege = {
                        onsaleid: vm.goodscontent.couponid,
                        onsale: vm.goodscontent.couponDiscount,
                        type: 3
                    };
                    OrdersShopsReq.ordersShopsPrivileges.push(privilege);
                }
                order.ordersShops.push(OrdersShopsReq);
                OrderService.createOrder(order).$promise.then(function (newOrder) {
                    loadCart(false, "leaveLoader");
                    //document.getElementById('payOrder').removeAttribute("disabled", "disabled");
                    if (newOrder.sumPrice < 0.001) {
                        input_alert("订单创建失败", 1000);
                        setTimeout(function () {
                            //$window.location.href = projectBaseUrl;
                        }, 1000);
                    }
                    else {
                        if (vm.goodscontent.couponid != '') {
                            var receiveCoupon = {
                                couponid: vm.goodscontent.couponid,
                                receiverid: userid,
                                status: 1
                            };
                            CouponService.saveByCouponIdAndRecId(receiveCoupon).$promise.then(function (data) {
                                //$state.go("morepay", {order: paramData});
                                var wxopenid = $localStorage.wxpay_openid;
                                /*!//跳转收款台
                                 window.location.href = jumpurl(newOrder.orderid, wxopenid, vm.shopid,vm.deskid);*/

                                //创建桌台
                                DeskService.modify_desk(vm.shopid, vm.deskid, {"status": 1}, function (deskinfo) {
                                    //alert(deskinfo);
                                    /*!//新增逻辑跳转选择余额支付
                                     //跳转收款台
                                     window.location.href = jumpurl(newOrder.orderid, wxopenid, vm.shopid,vm.deskid);*/
                                    $state.go("morepay",{orderid:newOrder.orderid,shopid:vm.shopid,appid:vm.appid,deskid:vm.deskid});
                                }, function (deskinfo) {
                                    //alert("1:" + JSON.stringify(deskinfo));
                                    input_alert("创建桌台失败", 1000);
                                })
                            })
                        } else {
                            //$state.go("morepay", {order: paramData});
                            var wxopenid = $localStorage.wxpay_openid;
                            /*!//跳转收款台
                             window.location.href = jumpurl(newOrder.orderid, wxopenid, vm.shopid,vm.deskid);*/
                            //创建桌台
                            DeskService.modify_desk(vm.shopid, vm.deskid, {"status": 1}, function (deskinfo) {
                                //alert(deskinfo);
                                /*!//新增逻辑跳转选择余额支付
                                 //跳转收款台
                                 window.location.href = jumpurl(newOrder.orderid, wxopenid, vm.shopid,vm.deskid);*/
                                $state.go("morepay",{orderid:newOrder.orderid,shopid:vm.shopid,appid:vm.appid,deskid:vm.deskid});
                            }, function (deskinfo) {
                                alert("2:" + JSON.stringify(deskinfo))
                                input_alert("创建桌台失败", 2000);
                            })
                        }
                    }
                }, function (error) {
                    if(error.data){
                        input_alert(error.data.reason, 2000);
                    }else{
                        input_alert("创建订单失败", 2000);
                    }
                    loadCart(false, "leaveLoader");
                    //document.getElementById('payOrder').removeAttribute("disabled", "disabled");
                    setTimeout(function () {
                        //$window.location.href = projectBaseUrl;
                    }, 1000);
                });
            }


        }

    };
    //选择可用优惠券
    vm.couponStatus =function(status){
        if (status == "show") {
            transformAnimation("-100%", 200, ".payment_show");
            transformAnimation(0, 200, ".choose_coupon");
        } else if (status == "hide") {
            transformAnimation(0, 200, ".payment_show");
            transformAnimation("100%", 200, ".choose_coupon");
        }
    };
    //选中当前优惠券
    vm.choose_coupon = function(coupon,couponList){
        if(!coupon.usable){
            return;
        }
        for(var i=0;i<couponList.length;i++){
            couponList[i].checked = false;
        }
        coupon.checked = true;
        vm.goodscontent.couponDiscount = coupon.discount;
        vm.goodscontent.couponid = coupon.couponid;
        vm.goodscontent.paymentprice =vm.goodscontent.totalprice - coupon.discount - vm.goodscontent.promotionDiscount;
        vm.couponStatus('hide');
    };
    //不使用优惠券
    vm.cancelCoupon = function(couponList){
        for(var i=0;i<couponList.length;i++){
            couponList[i].checked = false;
        }
        vm.goodscontent.couponDiscount = 0;
        vm.goodscontent.couponid = "";
        vm.goodscontent.paymentprice =vm.goodscontent.totalprice - vm.goodscontent.promotionDiscount;
        vm.couponStatus('hide');
    }
}